import { controller, action, routeData } from "maishu-node-mvc";
import { weixinDataContext } from "../common";
import { WeiXinDataContext } from "../data-context";
import { errors } from "../errors";
import { WeiXinSetting } from "../entities";
import { currentAppId } from "common";

@controller("setting")
export class Setting {

    @action()
    async item(@currentAppId appId: string, @weixinDataContext dc: WeiXinDataContext): Promise<WeiXinSetting> {
        if (!appId) throw errors.cannotGetApplicationId();
        let setting = await dc.settings.findOne(appId);
        return setting;
    }

    @action()
    async set(@currentAppId appId: string, @weixinDataContext dc: WeiXinDataContext, @routeData { item }: { item: WeiXinSetting }) {
        if (!appId) throw errors.cannotGetApplicationId();
        if (!item) throw errors.routeDataFieldNull("item");

        let setting = await dc.settings.findOne(appId);
        if (setting == null) {
            setting = item;
            setting.id = appId;
        }
        else {
            Object.assign(setting, item);
        }

        await dc.settings.save(setting);
        return { id: setting.id };
    }
}